//模块引用
var express = require('express');
var bodyParser = require('body-parser');  
var app = express();  
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
var fs = require('fs');
var path = require('path');
//逻辑定义
var root_path="/mnt/oss";
var domain_name="http://oss.baosoft.top";
app.get('/', function(request, response){  
  // 输出 JSON 格式  
   data = {  
       'application':'for upload file',  
       'author':'baoencheng  879612135@qq.com' , 
       'example1':'/upload  post   {"suffix":"jpg","file":"iVBORw0KGgoAA......."} file:base64 ' , 
       'example2':'/upload  post   {"suffix":"mp3","file":"iVBORw0KGgoAA......."} file:base64 ' , 
   };  
   console.log(data);  
   response.json(data);
});  
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })  
app.post('/upload',urlencodedParser, function(req, res){
    //接收前台POST过来的base64
	//console.log(req.body);
    var imgData = req.body.file;
    var suffix = "jpg";
    if(req.body.suffix){suffix = req.body.suffix;}
    //过滤data:URL
    var base64Data = imgData;
    var dataBuffer = new Buffer(base64Data, 'base64');
	var filename=randomWord(false,32);
	console.log(getDate());
	writeFile(root_path,getDate(),filename+"."+suffix,dataBuffer,res)
});  
var server = app.listen(8088, function(){
  var host = server.address().address;  
  var port = server.address().port;  
  console.log("address: %s, port: %d", host, port);  
});  
//返回随机字符串
function randomWord(randomFlag, min, max){
    var str = "",
        range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g','0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    // 随机产生
    if(randomFlag){
        range = Math.round(Math.random() * (max-min)) + min;
    }
    for(var i=0; i<range; i++){
        pos = Math.round(Math.random() * (arr.length-1));
        str += arr[pos];
    }
    return str;
}
//返回当前年月 存储时候按时间 分文件夹
function getDate(){
	var date=new Date;  
	var year=date.getFullYear();   
	var month=date.getMonth()+1;  
	var day=date.getDate();
	month =(month<10 ? "0"+month:month);   
	var mydate = "/material/"+(year.toString()+month.toString())+"/"+day+"/";
    return mydate;
}
//存储图片具体方法，如果没有路径 则创建路径后  再存储
 function writeFile(app_path,filepath,filename,dataBuffer,res){
        fs.writeFile(app_path+filepath+filename, dataBuffer, function(err) {
        if(err){
			if(err.code=="ENOENT"){
				console.log("baocuo");
				mkdir(app_path+filepath);
				writeFile(app_path,filepath,filename,dataBuffer,res);
			}
        }else{
          res.send(domain_name+filepath+filename);
        }
    });
 }
//使用时第二个参数可以忽略
function mkdir(dirpath,dirname){  
        //判断是否是第一次调用  
        if(typeof dirname === "undefined"){   
            if(fs.existsSync(dirpath)){  
                return;  
            }else{  
                mkdir(dirpath,path.dirname(dirpath));  
            }  
        }else{  
            //判断第二个参数是否正常，避免调用时传入错误参数  
            if(dirname !== path.dirname(dirpath)){   
                mkdir(dirpath);  
                return;  
            }  
            if(fs.existsSync(dirname)){  
                fs.mkdirSync(dirpath)  
            }else{  
                mkdir(dirname,path.dirname(dirname));  
                fs.mkdirSync(dirpath);  
            }  
        }  
}  

 
 
